package test2.spider.news.cnfol;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

import jodd.datetime.JDateTime;
import test2.spider.BaseProcessor;
import test2.spider.ThreadLocalUtil;

public class DetailProcessor extends BaseProcessor {
	
	private String url;
	private String channel;
	static Map<String, String> channelMap = new HashMap<>();
	
	static {
		channelMap.put("licaizixun", "理财资讯");
		channelMap.put("licaigonglue", "理财攻略");
		channelMap.put("caishenghuo", "财生活");
		channelMap.put("shoucangjingcui", "收藏精粹");
	}
	
	@Override
	protected String fetch(String url) {
		this.url = url;
		this.channel = channelMap.get(url.replaceFirst("http://money.cnfol.com/", "").split("/")[0]);
		return super.fetch(url);
	}

	@Override
	protected void parse(Document doc) {
		Element root = doc.select(".NewArt").get(0);
		String title = root.select("#Title").get(0).text().trim();
		Element sub = root.select(".Subtitle").get(0);
		String source = sub.select("#source_baidu").select("span").get(0).text().replaceFirst("来源：", "").trim();
		String author = sub.select("#author_baidu").get(0).text().replaceFirst("作者：", "").trim();
		String pubtime = sub.select("#pubtime_baidu").get(0).text().trim();
		
		System.err.println(pubtime);
		System.err.println(new JDateTime().toString("YYYY-MM-DD hh:mm"));
		boolean isold = new JDateTime(pubtime, "YYYY-MM-DD hh:mm").isBeforeDate(new JDateTime());
		System.err.println(isold);
		if(isold) return;
		
		String content = root.select("#Content").get(0).text().trim();
		Elements page = root.select("#page");
		if(CollectionUtils.isNotEmpty(page)) {
			String href = page.select("#pagenav_next").get(0).attr("href");
			ThreadLocalUtil.put("content", content);
			new DetailPageProcessor().process(href);
			content = ThreadLocalUtil.get("content");
		}
		Record news = new Record();
		news.set("title", title)
			.set("source", source)
			.set("author", author)
			.set("content", content)
			.set("pubtime", pubtime)
			.set("type", "中金在线")
			.set("channel", channel)
			.set("url", url);
		Db.save("news", news);
	}

}
